package cn.xutongxue.gtms.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.xutongxue.gtms.base.Errors;
import cn.xutongxue.gtms.entity.PostUserThesis;
import cn.xutongxue.gtms.entity.SelectUserThesis;
import cn.xutongxue.gtms.entity.Thesis;
import cn.xutongxue.gtms.entity.User;
import cn.xutongxue.gtms.entity.dto.user.UserQueryRequest;
import cn.xutongxue.gtms.entity.vo.TeacherGuideVo;
import cn.xutongxue.gtms.entity.vo.UserInfoVo;
import cn.xutongxue.gtms.entity.vo.UserVo;
import cn.xutongxue.gtms.exception.BusinessException;
import cn.xutongxue.gtms.mapper.UserMapper;
import cn.xutongxue.gtms.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
 * @createDate 2023-08-09 15:46:13
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserInfoVo login(String idNumber, String password, String role) {
        // 1. 校验
        if (StringUtils.isAnyBlank(idNumber, password, role)) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        // 2. 加密
        String encryptPassword = DigestUtil.md5Hex(password);
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_number", idNumber)
                .eq("password", encryptPassword)
                .eq("role", role);
        User user = getOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("login fail, idNumber: {}", idNumber);
            throw new BusinessException(Errors.PARAMS_ERROR, "用户名或密码错误");
        }
        // 3. 记录用户的登录态
        StpUtil.login(user.getId());
        return this.getUserInfoVo(user);
    }


    @Override
    public Page<UserVo> listUserVoByPage(UserQueryRequest userQueryRequest) {

        if (userQueryRequest == null) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }

        Long id = userQueryRequest.getId();
        String idNumber = userQueryRequest.getIdNumber();
        String username = userQueryRequest.getUsername();
        String role = userQueryRequest.getRole();
        long size = userQueryRequest.getSize();
        long current = userQueryRequest.getCurrent();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, User::getId, id)
                .eq(StringUtils.isNotBlank(idNumber), User::getIdNumber, idNumber)
                .like(StringUtils.isNotBlank(username), User::getUsername, username)
                .eq(StringUtils.isNotBlank(role), User::getRole, role);

        Page<User> userPage = page(new Page<>(current, size), null);
        Page<UserVo> userVoPage = new Page<>(current, size, userPage.getTotal());
        List<UserVo> userVO = this.getUserVO(userPage.getRecords());
        userVoPage.setRecords(userVO);
        return userVoPage;
    }

    @Override
    public UserVo getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVo userVO = new UserVo();
        BeanUtils.copyProperties(user, userVO);
        userVO.setEmail(DesensitizedUtil.email(user.getEmail()));
        userVO.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
        userVO.setPassword("");
        return userVO;
    }

    @Override
    public List<UserVo> getUserVO(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public Page<TeacherGuideVo> getStudentListByTeacherId(Long teacherId, Integer current, Integer size) {
        MPJLambdaWrapper<User> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(User.class)
                .select(Thesis::getTitle)
                .leftJoin(SelectUserThesis.class, SelectUserThesis::getUserId, User::getId)
                .leftJoin(Thesis.class, Thesis::getId, SelectUserThesis::getThesisId)
                .leftJoin(PostUserThesis.class, PostUserThesis::getThesisId, Thesis::getId  )
                .eq(PostUserThesis::getUserId, teacherId);
        return userMapper.selectJoinPage(new Page<>(current, size), TeacherGuideVo.class, wrapper);
    }

    @Override
    public Page<User> getAllTeacher(Integer current, Integer size) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole, "teacher");
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public Page<User> getAllStudent(Integer current, Integer size) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole, "student");
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public UserInfoVo getUserInfoVo(User user) {

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(user, userInfoVo);
        // 脱敏
        userInfoVo.setEmail(DesensitizedUtil.email(user.getEmail()));
        userInfoVo.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
        userInfoVo.setToken(StpUtil.getTokenValue());
        return userInfoVo;
    }

}




